package com.forum.utils;

import com.baomidou.mybatisplus.plugins.Page;
import org.apache.commons.lang3.StringUtils;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @ClassNameMyQuery
 * @Author 张继成
 * @Date 2023/11/15 15:05
 */
public class MyQuery<T> extends LinkedHashMap<String, Object> {
    private static final long serialVersionUID = 1L;

    /**
     *@Description //TODO Mybatis-puls分页参数
     *@Date 2023-11-15 15:12
     **/
    private Page<T> page;

    //当前页码
    private int currPage=1;

    //每页的条数
    private int limit=10;

    public MyQuery(JQPageInfo jqPageInfo){
        if (jqPageInfo.getPage() != null){
            currPage = jqPageInfo.getPage();
        }
        if (jqPageInfo.getLimit() !=null ){
            limit =jqPageInfo.getLimit();
        }

        //通过字符拼接的动态SQl，需要使用SQLFilter自定义的校验工具排查一些非法的字符，防止SQL注入的风险
        String Sidx = SQLFilter.sqlVerify(jqPageInfo.getSidx());
        String Order = SQLFilter.sqlVerify(jqPageInfo.getOrder());

        //Mybatis-puls分页
        this.page = new Page<>(currPage, limit);

        //排序
        if(StringUtils.isNotBlank(Sidx) && StringUtils.isNotBlank(Order)){
            this.page.setOrderByField(Sidx);
            this.page.setAsc("ASC".equalsIgnoreCase(Order));
        }
    }

    public MyQuery (Map<String, Object> params){
        this.putAll(params);

        if(params.get("page")!=null){
           currPage = Integer.parseInt(params.get("page").toString());
        }
        if (params.get("limit")!=null){
            limit=Integer.parseInt(params.get("limit").toString());
        }

        this.put("offset", (currPage - 1) * limit);
        this.put("page", currPage);
        this.put("limit", limit);

        //防止SQL注入（因为sidx、order是通过拼接SQL实现排序的，会有SQL注入风险）
        String sidx = SQLFilter.sqlVerify((String)params.get("sidx"));
        String order = SQLFilter.sqlVerify((String)params.get("order"));
        this.put("sidx", sidx);
        this.put("order", order);

        //mybatis-plus分页
        this.page = new Page<>(currPage, limit);

        //排序
        if(StringUtils.isNotBlank(sidx) && StringUtils.isNotBlank(order)){
            this.page.setOrderByField(sidx);
            this.page.setAsc("ASC".equalsIgnoreCase(order));
        }

    }

    public Page<T> getPage() {
        return page;
    }

    public int getCurrPage() {
        return currPage;
    }

    public int getLimit() {
        return limit;
    }
}
